<!--
 * @Author: zhangjingyu
 * @Date: 2020-11-15 16:15:47
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-04-14 17:42:15
 * @FilePath: \vprisk10.14\src\views\SystemMange\roleManage.vue
 * @Description: 角色管理
-->

<template>
  <!-- 角色管理页面 -->
  <div>
    <upper-template
      @search="(searchForm.page = 1), searchFunc()"
      @clear="(searchForm.roleCode = ''), (searchForm.roleName = '')"
    >
      <!-- 按钮区域 -->
      <div slot="buttonArea">
        <el-button @click="addFunc">新增</el-button>
        <el-button type="normal" @click="editFunc">编辑</el-button>
        <el-button type="normal" @click="delFunc">删除</el-button>
        <el-button type="normal" @click="roleConfig(0)">角色授权</el-button>
        <el-button type="normal" @click="roleConfig(1)"
          >可管理角色配置</el-button
        >
        <el-button type="normal" @click="roleConfig(2)">角色互斥配置</el-button>
        <!-- <el-button type="normal" @click="roleConfig(3)"
              >资源配置</el-button
            > -->
      </div>
      <!-- 导出区域 -->
      <div slot="exportArea"></div>
      导入区域
      <div slot="importArea"></div>
      <!-- 搜索区域 -->
      <div slot="searchArea">
        <el-form
          :model="searchForm"
          ref="searchForm"
          label-width="83px"
          label-position="left"
          size="mini"
        >
          <el-form-item label="角色编号：">
            <el-input
              v-model="searchForm.roleCode"
              style="width:150px"
              @keydown.enter.native="searchFunc()"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色名称：">
            <el-input
              v-model="searchForm.roleName"
              style="width:150px"
              @keydown.enter.native="searchFunc()"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <!-- 列表显示隐藏操作区 -->
      <div slot="columnHide">
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="item in textData"
            :label="item.label"
            :key="item.prop"
            >{{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </upper-template>
    <!-- 表格区域 -->
    <el-table
      ref="multipleTable"
      :data="tableData"
      style="width: 100%"
      @row-click="authorizeFor"
    >
      <el-table-column
        width="55"
        type="selection"
        
      ></el-table-column>
      <el-table-column
        prop="roleCode"
        label="角色编号"
        align="left"
        v-if="columnState[0]"
      >
      </el-table-column>
      <el-table-column
        prop="roleName"
        label="角色姓名"
        show-overflow-tooltip
        align="left"
        sortable
        v-if="columnState[1]"
      >
      </el-table-column>
      <el-table-column
        prop="roleDesc"
        label="角色描述"
        align="left"
        sortable
        show-overflow-tooltip
        v-if="columnState[2]"
      >
      </el-table-column>

      <el-table-column
        prop="mgrRole"
        label="可管理角色"
        align="left"
        sortable
        v-if="columnState[3]"
        show-overflow-tooltip
        :formatter="
          row => {
            return row.mgrRole.map(v => v.roleName).toString();
          }
        "
      >
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @refresh="searchFunc"
      :current-page="searchForm.page"
      :page-size="searchForm.size"
      :total="total"
    ></pagination>
    <!-- 新增/修改弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="saveTitles[saveFlg - 1]"
      :visible.sync="addOrEdit"
      width="514px"
    >
      <el-form
        :model="saveForm"
        ref="saveForm"
        label-width="97px"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色编码：" prop="roleCode">
              <el-input
                v-if="saveFlg == 1"
                v-model="saveForm.roleCode"
                maxlength="35"
              >
                <template slot="prepend">ROLE_</template>
              </el-input>
              <el-input
                v-else
                v-model="saveForm.roleCode"
                maxlength="35"
                :disabled="saveFlg == 2"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色名称：" prop="roleName">
              <el-input v-model="saveForm.roleName" maxlength="40"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色描述：" prop="roleDesc">
              <el-input
                type="textarea"
                v-model="saveForm.roleDesc"
                maxlength="40"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="管理角色："
              prop="supRoleId"
              v-if="saveFlg == 1"
            >
              <el-select
                v-model="saveForm.supRoleId"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  v-for="item in supRoleIdList"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveFunc">确 定</el-button>
        <el-button @click="quxiaoFunc">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 配置弹窗 -->
    <el-dialog
      :title="'为' + userName + userDo"
      v-dialogDrag
      :visible.sync="isConfig"
      class="dialog-auto-height"
      width="40%"
    >
      <vp-tree
        vp-title="菜单选择"
        :footerBtn="false"
        v-show="userDoFlag == 0"
        :data="treeData"
        :props="defaultProps"
        @node-click="handleNodeClick"
        default-expand-all
        show-checkbox
        ref="configTree"
        node-key="id"
        :expand-on-click-node="false"
        check-on-click-node
      ></vp-tree>
      <el-table
        v-show="userDoFlag == 1 || userDoFlag == 2"
        ref="roleTable"
        :data="tableDataRole"
        style="width: 100%"
      >
        <el-table-column
          width="55"
          type="selection"
          
        ></el-table-column>
        <el-table-column
          prop="roleCode"
          label="角色编号"
          sortable
        ></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
          sortable
        ></el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="saveConfigTree" v-if="userDoFlag == 0"
          >确定</el-button
        >
        <el-button
          @click="saveConfigTable"
          v-if="userDoFlag == 1 || userDoFlag == 2"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { systemManage } from "@/api/index";
import { listToTree } from "@/lib/util";

export default {
  data() {
    return {
      userName: "", //右侧用户名
      userDo: "授权", // 右侧用户行为
      userDoFlag: 0,
      addOrEdit: false, // 新增/编辑/查看弹窗
      isConfig: false,
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      saveTitles: ["添加新角色", "编辑角色信息"],
      // 机构树
      orgList: [
        {
          value: "01",
          label: "一级机构",
          children: [{ value: "001", label: "二级机构" }]
        }
      ],
      // 右侧树data
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      clickRow: {},
      // 角色管理下拉框
      supRoleIdList: [],
      // search机构树悬停提示
      searchOrgTip: "",
      // save表单机构树悬停提示
      saveOrgTip: "",
      searchForm: {
        page: 1,
        size: 15,
        roleCode: "",
        roleName: ""
      },
      total: 0,
      saveForm: {},
      saveFormRules: {
        roleCode: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          },
          {
            pattern: /^[0-9a-zA-Z_]{0,50}$/,
            message: "只能输入英文字母、数字、下划线",
            trigger: "blur"
          }
          // { validator: this.validRoleCode, trigger: "blur" }
        ],
        roleName: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
            message: "只能输入中文、英文字母、数字和下划线",
            trigger: "blur"
          }
        ],
        roleDesc: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
            message: "只能输入中文、英文字母、数字和下划线",
            trigger: "blur"
          }
        ],
        supRoleId: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          }
        ]
      },
      checkList: [],
      // 完整表头字段&&列属性配置
      textData: [
        { prop: "roleCode", label: "角色编号" },
        { prop: "roleName", label: "角色名称" },
        { prop: "roleDesc", label: "角色描述 " },
        { prop: "mgrRole", label: "可管理角色" }
      ],
      // 获取table的数据
      tableData: [],
      tableDataRole: []
    };
  },
  created() {
    this.checkListInit();
    // console.log(this.tableData, '模拟数据')
  },
  computed: {
    columnState() {
      console.log(this.checkList);
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    }
  },
  mounted() {
    this.getAllRoles();
    this.searchFunc();
  },
  watch: {
    addOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    }
  },
  methods: {
    // 两个密码校验
    validRoleCode(rule, value, callback) {
      let str = this.saveForm.roleCode;
      if (str.substring(0, 5) === "ROLE_") {
        console.log(str);
        callback();
      } else {
        callback(new Error("角色编码必须以“ROLE_”开头"));
      }
    },
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    // 管理角色下拉框
    getAllRoles() {
      systemManage.getAllRole().then(res => {
        if (res.code == 200) {
          console.log(res);
          this.supRoleIdList = res.datas;
        }
      });
    },
    // 可管理角色配置表
    getTableDataRole(row) {
      systemManage
        .roleConfigTable({ roleId: row.roleId })
        .then(res => {
          if (res.code == 200) {
            this.tableDataRole = res.datas;
            // 回显选中可管理角色或角色互斥
            this.$nextTick(() => {
              if (this.userDoFlag == 1) {
                this.showMyRoles(row);
              } else {
                this.showRoleMutex(row);
              }
            });
          }
        })
        .catch(err => {});
    },
    // 回显可管理角色
    showMyRoles(row) {
      console.log(row);
      for (let i = 0; i < row.mgrRole.length; i++) {
        for (let j = 0; j < this.tableDataRole.length; j++) {
          if (row.mgrRole[i].roleId == this.tableDataRole[j].roleId) {
            let setRow = this.tableDataRole[j];
            this.$refs.roleTable.toggleRowSelection(setRow, true);
          }
        }
      }
    },
    // 回显互斥角色
    showRoleMutex(row) {
      for (let i = 0; i < row.roleMutex.length; i++) {
        for (let j = 0; j < this.tableDataRole.length; j++) {
          if (
            row.roleMutex[i].roleMutexCode == this.tableDataRole[j].roleCode
          ) {
            let setRow = this.tableDataRole[j];
            this.$refs.roleTable.toggleRowSelection(setRow, true);
          }
        }
      }
    },
    // 查询
    searchFunc() {
      let data = this.searchForm;
      console.log(data);
      systemManage
        .roleManageQuery(data)
        .then(res => {
          if (res.code == 200) {
            this.tableData = res.datas.rows;
            this.total = res.datas.total;
            // 默认传入第一行的数据到右侧，默认为授权角色
            // this.$nextTick(() => {
            //     this.authorizeFor(this.tableData[0])
            // })
          }
        })
        .catch(err => {});
    },
    addFunc() {
      this.saveFlg = 1;
      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.addOrEdit = true;
    },
    editFunc() {
      this.saveFlg = 2;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      let form = { ...row };
      this.saveForm = form;
      this.addOrEdit = true;
    },

    saveFunc() {
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.saveForm))
          if (this.saveFlg == "1") {
            data.roleCode = "ROLE_" + data.roleCode;
          }
          systemManage
            .roleManageSave(data)
            .then(res => {
              if (res.code == 200) {
                this.$message.success("保存成功");
                this.addOrEdit = false;
                this.searchFunc();
              } else {
                this.$message.error(res.message);
              }
            })
            .catch(err => {});
        }
      });
    },
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中的角色吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = { ids: selection.map(v => v.roleId) };
          systemManage
            .removeRole(data)
            .then(res => {
              if (res.code == 200) {
                this.$message.success("删除成功");
                this.searchFunc();
              } else {
                this.$message.error(res.message);
              }
            })
            .catch(err => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleNodeClick() {
      let nodes = this.$refs.configTree.$tree.getCheckedNodes();
      console.log(nodes);
    },
    // 点击表格行
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
      this.clickRow = row;
    },

    roleConfig(val) {
      let arr = [" 授权", " 配置可管理角色", " 配置角色互斥", " 配置资源 "];
      let checked = this.$refs.multipleTable.selection;
      this.clickRow = checked[0];
      if (checked.length < 1) {
        return this.$message.warning("请选择一条数据");
      } else if (checked.length > 1) {
        return this.$message.warning("只能选择一条数据");
      } else {
        this.userDo = arr[val];
        this.userDoFlag = val;
        this.isConfig = true;
        let row = checked[0];
        this.userName = row.roleName;
        if (val == 1 || val == 2) {
          // 可管理角色配置和角色互斥
          this.getTableDataRole(row);
        } else if (val == 0) {
          // 角色授权菜单
          this.getMenuOfRole(row);
        }
      }
    },
    // 通过roleId获取菜单树
    getMenuOfRole(row) {
      let data = { roleId: row.roleId };
      systemManage.getRoleMenu(data).then(res => {
        let list = res.datas;
        // 获取选中的id
        let checkedNodes = [];
        for (let i = 0; i < list.length; i++) {
          list[i].disabled = list[i].chkDisabled;
          if (list[i].checked == true) {
            checkedNodes.push(list[i]);
          }
        }
        console.log(checkedNodes, "checkedNodes");
        this.treeData = listToTree("id", "pId", res.datas);
        // 回显选中
        console.log(this.treeData);
        this.$nextTick(() => {
          this.$refs.configTree.$tree.setCheckedNodes(checkedNodes);
        });
      });
    },
    // 保存选中菜单
    saveConfigTree() {
      let data = {
        roleId: this.clickRow.roleId,
        ids: this.$refs.configTree.$tree.getCheckedNodes().map(v => v.id),
        // 所属模块
        moduleCode: this.$refs.configTree.$tree
          .getCheckedNodes()
          .map(v => v.moduleCode)
      };
      systemManage.saveRoleMenuChecked(data).then(res => {
        if (res.code == 200) {
          this.$message.success("保存成功");
          this.isConfig = false;
          // 刷新表
          this.searchFunc();
        }
      });
    },
    saveConfigTable() {
      if (this.userDoFlag == 1) {
        let mgrIds = this.$refs.roleTable.selection.map(v => v.roleId);
        let data = {
          roleId: this.clickRow.roleId,
          mgrIds: mgrIds
        };
        systemManage
          .saveMgrRole(data)
          .then(res => {
            if (res.code == 200) {
              console.log(res);
              this.$message.success("保存成功");
              this.isConfig = false;
              // 刷新表
              this.searchFunc();
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(err => {});
      } else {
        let mutexIds = this.$refs.roleTable.selection.map(v => v.roleId),
          mutexCodes = this.$refs.roleTable.selection.map(v => v.roleCode);
        let data = {
          roleId: this.clickRow.roleId,
          roleCode: this.clickRow.roleCode,
          mutexIds: mutexIds,
          mutexCodes: mutexCodes
        };
        systemManage
          .saveRoleMutex(data)
          .then(res => {
            if (res.code == 200) {
              console.log(res);
              this.$message.success("保存成功");
              this.isConfig = false;
              // 刷新表
              this.searchFunc();
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(err => {});
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    handleCurrentChange(val) {
      this.searchForm.page = val;
      console.log(`当前页: ${val}`);
      this.searchFunc();
    },
    quxiaoFunc() {
      this.addOrEdit = false;
      this.$refs.saveForm.clearValidate();
    }
  }
};
</script>

<style lang="scss" scoped>
// /deep/.noAutoHight .el-dialog__body{
//     // overflow:hidden;
//     height: 604px;
// }
</style>